const express = require('express');
const admin = require("../model/admin")
const mongoose = require("mongoose")
const bcrypt = require("bcrypt")
const uuid = require("node-uuid");
const jwt = require("jsonwebtoken")
const constant = require('../constant/constant')
const activity = require('../model/activity')
const router = express.Router();

mongoose.connect("mongodb://119.23.230.239:27017/cvte");
const secretKey = constant.secretKey
const header = "Bearer";
const host = "127.0.0.1" //前端nginx配置的路径
router.post("/register",async(req,res)=>{
    let {username,password} = req.body;
    const doc = await admin.findOne({username});
    try {
        if(doc){ //已存在
            res.status(403)
            res.json({
                status:'1',
                msg:'用户名已存在',
            })
        }
        else {
           const saltRounds =10;
            bcrypt.genSalt(saltRounds,function (err,salt) {
                bcrypt.hash(password,salt,function (err,hash) {
                    password = hash;
                    admin.create({
                        'username':username,
                        'password':password
                    })
                    res.json({
                        status:'0',
                        msg:"用户注册成功",
                    })
                })
            })

        }
    }catch (e) {
        if(e){
            res.json({
                status:'1',
                msg:e.message,
            })
        }
    }
})
router.post('/login',async (req,res)=>{
    let {username,password} = req.body;
    const doc  = await admin.findOne({username});
    try{
        if(doc){
            bcrypt.compare(password,doc.password,(err,isvalid)=>{
                if(isvalid){ //合法
                    let token  = jwt.sign({user:username},secretKey,{
                        expiresIn: 60*60*24
                    });
                    res.json({
                        status:'0',
                        msg:'登录成功',
                        token:token,
                        header:header
                    })
                }else {
                    res.status(404);
                    res.json({
                        status:'1',
                        msg:"密码错误",
                    })
                }
            })
        }else {
            res.status(404);
            res.json({
                status:'1',
                msg:"没有该用户",
            })
        }
    }catch (e) {
        res.status(500);
        res.json({
            status:'1',
            msg:e.message,
        })
    }
})
//活动的一系列操作
router.post("/save",async (req,res)=>{
    let {tag,activity_title,start_time,end_time,costIntegral,drwasNum,drawsType,prize}= req.body;
    let activity_id = uuid.v1();
    let url = host+`/user/${activity_id}`
    let qrcode = new Buffer(url).toString('base64');
    let username = req.get("Authorization");
    let doc = await activity.create({
        "activity_id":activity_id,
        'tag':tag,
        'activity_title':activity_title,
        'start_time':start_time,
        'end_time':end_time,
        'costIntegral':costIntegral,
        'url':url,
        'qrCode':qrcode,
        'status':0,
        'participateNum':0,
        'creator_name':username,
        'drawsNum':drwasNum,
        'drawsType':drawsType,
        'prize':prize
    })
    try{
        if(doc){
            res.json({
                status:'0',
                msg:'保存成功'
            })
        }
        else {
            res.status(500)
            res.json({
                status:'1',
                msg:"保存出错"
            })
        }
    }catch (e) {
        res.json({
            status:'0',
            msg:e.message
        })
    }
})
router.post("/saveAndIssue",async (req,res)=>{
    let {tag,activity_title,start_time,end_time,costIntegral,drawsNum,drawsType,prize}= req.body;
    let activity_id = uuid.v1();
    let url = host+`/user/${activity_id}`
    let qrcode = new Buffer(url).toString('base64');
    let username = req.get("Authorization");
    let doc = await activity.create({
        "activity_id":activity_id,
        'tag':tag,
        'activity_title':activity_title,
        'start_time':start_time,
        'end_time':end_time,
        'costIntegral':costIntegral,
        'url':url,
        'qrCode':qrcode,
        'status':1,
        'participateNum':0,
        'creator_name':username,
        'drawsNum':drawsNum,
        'drawsType':drawsType,
        'prize':prize
    })
    try{
        if(doc){
            res.json({
                status:'0',
                msg:"保存并且发布成功",
                url:url,
                qrcode:qrcode
            })
        }else {
            res.status(500)
            res.json({
                status:'1',
                msg:"保存并且发布失败"
            })
        }
    }catch (e) {
        res.status(500)
        res.json({
            status:'1',
            msg:e.message
        })
    }
})
//test authorization
router.post("/test",async (req,res)=>{
    const Authorization = req.headers['authorization'];
    res.json({
        name:req.headers["authorization"]
    })

})
module.exports = router